package com.boge.ratelimiter.valve.impl;

import com.alibaba.fastjson.JSON;
import com.boge.ratelimiter.Constants;
import com.boge.ratelimiter.annotation.DoRateLimiter;
import com.boge.ratelimiter.valve.IValveService;
import com.google.common.util.concurrent.RateLimiter;
import org.aspectj.lang.ProceedingJoinPoint;

import java.lang.reflect.Method;

public class RateLimiterValve implements IValveService {


    /**
     *  处理切面拦截到方法，做限流处理
     */
    @Override
    public Object access(ProceedingJoinPoint jp, Method method, DoRateLimiter annotation, Object[] args) throws Throwable {
        // 01：判断是否进行限流
        if(0 == annotation.permitsPersecond()) return jp.proceed();

        // 02: 获取map中的key
        String clazzName = jp.getTarget().getClass().getName();
        String methodName = method.getName();
        String mapKey = clazzName+"."+methodName;
        // 03: 查看map中是否有值
        if(null == Constants.rateLimiterMap.get(mapKey))
            Constants.rateLimiterMap.put(mapKey, RateLimiter.create(annotation.permitsPersecond()));

        RateLimiter rateLimiter = Constants.rateLimiterMap.get(mapKey);
        if(rateLimiter.tryAcquire()) return jp.proceed();

        return JSON.parseObject(annotation.returnJson(), method.getReturnType());
    }
}

  